<template>
  <div class="employee-container">
    <el-card>
      <div slot="header" class="card-header">
        <h2>员工管理系统</h2>
        <el-button type="primary" @click="openAddDialog">
          <i class="el-icon-plus"></i> 新增员工
        </el-button>
      </div>

      <!-- 筛选和搜索区域 -->
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="部门">
          <el-select v-model="filters.department" placeholder="请选择部门" @change="handleFilterChange">
            <el-option label="技术部" value="技术部"></el-option>
            <el-option label="市场部" value="市场部"></el-option>
            <el-option label="人事部" value="人事部"></el-option>
            <el-option label="财务部" value="财务部"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="请选择状态" @change="handleFilterChange">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
            <el-option label="休假" value="休假"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学历">
          <el-select v-model="filters.degree" placeholder="请选择学历" @change="handleFilterChange">
            <el-option label="本科" value="本科"></el-option>
            <el-option label="硕士" value="硕士"></el-option>
            <el-option label="博士" value="博士"></el-option>
            <el-option label="大专" value="大专"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="filters.gender" placeholder="请选择性别" @change="handleFilterChange">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入职时间">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchKey" placeholder="搜索姓名/工号/手机号" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div class="batch-operation">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除 ({{ selectedIds.length }})
        </el-button>
      </div>

      <!-- 员工列表 -->
      <el-table
          :data="employees"
          border
          stripe
          @selection-change="handleSelectionChange"
          style="width: 100%; margin-top: 15px;"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="work_id" label="工号" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="department" label="部门" width="120"></el-table-column>
        <el-table-column prop="position" label="职位" width="150"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="130"></el-table-column>
        <el-table-column prop="degree" label="学历" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '在职' ? 'success' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entry_time" label="入职时间" width="150"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          style="margin-top: 15px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 新增员工弹窗 -->
    <el-dialog
        title="新增员工"
        :visible.sync="addDialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="100px"
          class="add-form"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="工号" prop="work_id">
          <el-input v-model="addForm.work_id" placeholder="请输入工号"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="addForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="department">
          <el-select v-model="addForm.department" placeholder="请选择部门">
            <el-option label="技术部" value="技术部"></el-option>
            <el-option label="市场部" value="市场部"></el-option>
            <el-option label="人事部" value="人事部"></el-option>
            <el-option label="财务部" value="财务部"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-input v-model="addForm.position" placeholder="请输入职位"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="id_number">
          <el-input v-model="addForm.id_number" placeholder="请输入身份证号"></el-input>
        </el-form-item>

        <el-form-item label="学历" prop="degree">
          <el-select v-model="addForm.degree" placeholder="请选择学历">
            <el-option label="本科" value="本科"></el-option>
            <el-option label="硕士" value="硕士"></el-option>
            <el-option label="博士" value="博士"></el-option>
            <el-option label="大专" value="大专"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
            <el-option label="休假" value="休假"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入职时间" prop="entry_time">
          <el-date-picker
              v-model="addForm.entry_time"
              type="date"
              placeholder="选择入职时间"
              value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 基础配置
const API_BASE_URL = 'http://localhost:8000/api'; // 替换为你的API地址

// 响应式数据
const employees = ref([]);
const totalCount = ref(0);
const page = ref(1);
const pageSize = ref(10);
const selectedIds = ref([]);
const searchKey = ref('');
const dateRange = ref([]);
const addDialogVisible = ref(false);

// 筛选条件
const filters = reactive({
  department: '',
  status: '',
  degree: '',
  gender: ''
});

// 新增员工表单数据
const addForm = reactive({
  name: '',
  work_id: '',
  gender: '',
  department: '',
  position: '',
  phone: '',
  id_number: '',
  degree: '',
  status: '在职', // 默认在职
  entry_time: ''
});

// 新增表单验证规则
const addFormRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  work_id: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  entry_time: [
    { required: true, message: '请选择入职时间', trigger: 'change' }
  ]
});

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 获取员工列表
const fetchEmployees = async () => {
  try {
    // 构建查询参数
    const params = new URLSearchParams();

    // 添加筛选条件
    Object.keys(filters).forEach(key => {
      if (filters[key]) params.append(key, filters[key]);
    });

    // 添加搜索关键词
    if (searchKey.value) {
      params.append('search', searchKey.value);
    }

    // 添加日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.append('entry_start', dateRange.value[0].toISOString().split('T')[0]);
      params.append('entry_end', dateRange.value[1].toISOString().split('T')[0]);
    }

    // 添加分页参数
    params.append('page', page.value);
    params.append('page_size', pageSize.value);

    // 调用API
    const response = await axios.get(`${API_BASE_URL}/employees/search/`, { params });

    // 更新数据
    employees.value = response.data.employees;
    totalCount.value = response.data.count;
  } catch (error) {
    ElMessage.error('获取员工列表失败，请重试');
    console.error(error);
  }
};

// 打开新增员工弹窗
const openAddDialog = () => {
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = key === 'status' ? '在职' : '';
  });
  if (proxy.$refs.addFormRef) {
    proxy.$refs.addFormRef.resetFields();
  }
  addDialogVisible.value = true;
};

// 提交新增表单
const submitAddForm = async () => {
  try {
    // 表单验证
    await proxy.$refs.addFormRef.validate();

    // 提交数据到后端
    const response = await axios.post(`${API_BASE_URL}/employees/`, addForm);

    // 显示成功消息
    ElMessage.success('员工添加成功');

    // 关闭弹窗
    addDialogVisible.value = false;

    // 重新获取员工列表
    fetchEmployees();
  } catch (error) {
    if (error.name === 'Error') {
      // 表单验证失败不显示错误消息
      return;
    }
    ElMessage.error(error.response?.data?.message || '添加员工失败，请重试');
    console.error(error);
  }
};

// 处理搜索
const handleSearch = () => {
  page.value = 1; // 重置页码
  fetchEmployees();
};

// 处理筛选条件变化
const handleFilterChange = () => {
  page.value = 1;
  fetchEmployees();
};

// 处理日期范围变化
const handleDateChange = () => {
  page.value = 1;
  fetchEmployees();
};

// 重置筛选条件
const resetFilters = () => {
  Object.keys(filters).forEach(key => {
    filters[key] = '';
  });
  searchKey.value = '';
  dateRange.value = [];
  page.value = 1;
  fetchEmployees();
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return;

  try {
    const response = await axios.post(`${API_BASE_URL}/employees/batch_delete/`, {
      ids: selectedIds.value
    });

    ElMessage.success(response.data.message);
    fetchEmployees(); // 重新获取列表
    selectedIds.value = []; // 清空选择
  } catch (error) {
    ElMessage.error(error.response?.data?.error || '批量删除失败');
    console.error(error);
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchEmployees();
};

const handleCurrentChange = (val) => {
  page.value = val;
  fetchEmployees();
};

// 页面加载时获取数据
onMounted(() => {
  fetchEmployees();
});
</script>

<style scoped>
.employee-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 15px;
}

.batch-operation {
  margin-bottom: 10px;
  text-align: left;
}

.add-form {
  margin-top: 15px;
}
</style>
